package com.example.springboot02amqp.dao;

import com.example.springboot02amqp.vo.AddressExcelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: 喵喵~
 * Date: 2023/2/10
 * Time: 1:24
 * Description:
 */
@Component
public class AddressDao {
    @Autowired
    StringRedisTemplate redisTemplate;

    public void insert(String projectCode, AddressExcelVO addressExcelVO) {
        String key = projectCode + ":" + addressExcelVO.getLevel() + ":" + addressExcelVO.getAddressName();
        redisTemplate.opsForValue().set(key, addressExcelVO.getAddressCode(), 10, TimeUnit.MINUTES);
    }

    public void insertBatch(String projectCode, List<AddressExcelVO> addressExcelVOS) {
        // 管道插入
        RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                addressExcelVOS.forEach(vo -> {
                    String key = projectCode + ":" + vo.getLevel() + ":" + vo.getAddressName();
                    //System.out.println(key);
                    redisConnection.set(serializer.serialize(key),
                            serializer.serialize(vo.getAddressCode()),
                            Expiration.seconds(600), RedisStringCommands.SetOption.UPSERT);
                });
                return null;
            }
    });
    }
}
